package com.gx.util.dbutil;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by gx on 2017/7/7.
 */
public class TransactionManager {
    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    public static Connection getConnection(){
        try {
            Connection conn = tl.get();//从当前线程上获取链接
            if(conn==null){
                conn = DBUtilsHelper.getDataSource().getConnection();//没有就从池中取一个
                tl.set(conn);//绑定到当前线程上
            }
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException("从数据源获取链接失败");
        }
    }

    public static void startTransaction(){
        Connection conn = getConnection();
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }//开始事务
    }
    public static void commit(){
        Connection conn = getConnection();
        try {
            conn.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void rollback(){
        Connection conn = getConnection();
        try {
            conn.rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void release(){
        Connection conn = getConnection();
        try {
            conn.close();
            tl.remove();//从当前线程上解绑。（服务器用到了线程池的技术）
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
